import { defineStore } from 'pinia'
import {
  ServeCustomizeEmoticonList,
  ServeCustomizeEmoticonUpload,
  ServeCustomizeEmoticonDelete
} from '@/api/emoticon'

import { toApi } from '@/api'

export const useEditorStore = defineStore('editor', {
  state: () => {
    return {
      // 表包相关
      emoticon: {
        items: [
          {
            name: '系统表情',
            icon: '',
            children: [] as any[]
          },
          {
            name: '我的收藏',
            icon: '',
            children: [] as any[]
          }
        ]
      }
    }
  },
  actions: {
    // 加载用户表情包
    async loadUserEmoticon() {
      const {
        code,
        data: { items }
      } = await toApi(ServeCustomizeEmoticonList)

      if (code != 200) return

      this.emoticon.items[1].children = items || []
    },

    // 自定义上传用户表情包
    async uploadUserEmoticon(file: File) {
      const params = new FormData()
      params.append('file', file)

      const { code, data } = await toApi(ServeCustomizeEmoticonUpload, params)

      if (code != 200) return

      this.emoticon.items[1]?.children?.unshift(data)
    },

    // 删除自定义上传用户表情包
    async removeUserEmoticon(resoure: { index: number; emoticon_id: number }) {
      const { index, emoticon_id } = resoure

      const { code } = await toApi(
        ServeCustomizeEmoticonDelete,
        { emoticon_id },
        {
          showMessageText: '删除成功'
        }
      )

      if (code != 200) return

      this.emoticon.items[1]?.children.splice(index, 1)
    }
  }
})
